const cloud = require("wx-server-sdk");
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();

// 获取openid
const getOpenId = async () => {
  const wxContext = cloud.getWXContext();
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
};

// 自律系统数据操作
const sleepRecord = async (event) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  
  if (!openid) {
    return {
      success: false,
      message: '用户未登录'
    };
  }

  const sleepCollection = db.collection('sleepRecords');
  
  try {
    switch (event.action) {
      case 'add':
        // 添加打卡记录
        const record = {
          ...event.data,
          openid: openid,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        };
        
        await sleepCollection.add({
          data: record
        });
        
        return {
          success: true,
          message: '打卡记录已保存'
        };
        
      case 'update':
        // 更新打卡记录
        const { _id, ...updateData } = event.data;
        await sleepCollection.doc(_id).update({
          data: {
            ...updateData,
            updateTime: db.serverDate()
          }
        });
        
        return {
          success: true,
          message: '记录已更新'
        };
        
      case 'delete':
        // 删除打卡记录
        await sleepCollection.doc(event.data._id).remove();
        
        return {
          success: true,
          message: '记录已删除'
        };
        
      case 'getList':
        // 获取用户打卡记录列表
        const { data: records } = await sleepCollection.where({
          openid: openid
        }).orderBy('createTime', 'desc').get();
        
        return {
          success: true,
          data: records
        };
        
      case 'getToday':
        // 获取今日打卡记录
        const today = new Date();
        const todayStr = today.toISOString().split('T')[0];
        
        const { data: todayRecords } = await sleepCollection.where({
          openid: openid,
          date: todayStr
        }).get();
        
        return {
          success: true,
          data: todayRecords
        };
        
      case 'getWeekly':
        // 获取本周统计
        const weekStart = new Date();
        weekStart.setDate(weekStart.getDate() - 7);
        
        const { data: weeklyRecords } = await sleepCollection.where({
          openid: openid,
          createTime: db.command.gte(weekStart)
        }).get();
        
        return {
          success: true,
          data: weeklyRecords
        };
        
      default:
        return {
          success: false,
          message: '未知操作'
        };
    }
  } catch (error) {
    console.error('自律系统操作错误:', error);
    return {
      success: false,
      message: '操作失败',
      error: error.message
    };
  }
};

// 健康系统数据操作
const moodRecord = async (event) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  
  if (!openid) {
    return {
      success: false,
      message: '用户未登录'
    };
  }

  const moodCollection = db.collection('moodRecords');
  
  try {
    switch (event.action) {
      case 'add':
        // 添加心情记录
        const record = {
          ...event.data,
          openid: openid,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        };
        
        await moodCollection.add({
          data: record
        });
        
        return {
          success: true,
          message: '心情记录已保存'
        };
        
      case 'update':
        // 更新心情记录
        const { _id, ...updateData } = event.data;
        await moodCollection.doc(_id).update({
          data: {
            ...updateData,
            updateTime: db.serverDate()
          }
        });
        
        return {
          success: true,
          message: '记录已更新'
        };
        
      case 'delete':
        // 删除心情记录
        await moodCollection.doc(event.data._id).remove();
        
        return {
          success: true,
          message: '记录已删除'
        };
        
      case 'getList':
        // 获取用户心情记录列表
        const { data: records } = await moodCollection.where({
          openid: openid
        }).orderBy('createTime', 'desc').get();
        
        return {
          success: true,
          data: records
        };
        
      case 'getToday':
        // 获取今日心情记录
        const today = new Date();
        const todayStr = today.toISOString().split('T')[0];
        
        const { data: todayRecords } = await moodCollection.where({
          openid: openid,
          date: todayStr
        }).get();
        
        return {
          success: true,
          data: todayRecords
        };
        
      case 'getWeekly':
        // 获取本周统计
        const weekStart = new Date();
        weekStart.setDate(weekStart.getDate() - 7);
        
        const { data: weeklyRecords } = await moodCollection.where({
          openid: openid,
          createTime: db.command.gte(weekStart)
        }).get();
        
        return {
          success: true,
          data: weeklyRecords
        };
        
      default:
        return {
          success: false,
          message: '未知操作'
        };
    }
  } catch (error) {
    console.error('健康系统操作错误:', error);
    return {
      success: false,
      message: '操作失败',
      error: error.message
    };
  }
};

// 用户数据同步
const syncUserData = async (event) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  
  if (!openid) {
    return {
      success: false,
      message: '用户未登录'
    };
  }

  try {
    const { localData, dataType } = event;
    
    if (dataType === 'sleepRecords') {
      const sleepCollection = db.collection('sleepRecords');
      
      // 清除旧数据
      await sleepCollection.where({
        openid: openid
      }).remove();
      
      // 批量插入新数据
      if (localData && localData.length > 0) {
        const records = localData.map(item => ({
          ...item,
          openid: openid,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }));
        
        for (let record of records) {
          await sleepCollection.add({
            data: record
          });
        }
      }
      
      return {
        success: true,
        message: '自律数据同步成功'
      };
    }
    
    if (dataType === 'moodRecords') {
      const moodCollection = db.collection('moodRecords');
      
      // 清除旧数据
      await moodCollection.where({
        openid: openid
      }).remove();
      
      // 批量插入新数据
      if (localData && localData.length > 0) {
        const records = localData.map(item => ({
          ...item,
          openid: openid,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }));
        
        for (let record of records) {
          await moodCollection.add({
            data: record
          });
        }
      }
      
      return {
        success: true,
        message: '健康数据同步成功'
      };
    }
    
    return {
      success: false,
      message: '未知数据类型'
    };
    
  } catch (error) {
    console.error('数据同步错误:', error);
    return {
      success: false,
      message: '同步失败',
      error: error.message
    };
  }
};

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.type) {
    case "login":
      return await getOpenId();
    case "sleepRecord":
      return await sleepRecord(event);
    case "moodRecord":
      return await moodRecord(event);
    case "syncUserData":
      return await syncUserData(event);
    default:
      return {
        success: false,
        message: '未知的操作类型'
      };
  }
};
